package com.dog.view.utils;

import javax.faces.FacesException;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * User: Kuttubek Aidaraliev
 * Date: 11.05.2010
 * Time: 10:15:26
 */
public class EnumSelectItems {

    public static <E extends Enum>List<SelectItem> getSelectItems(Class<E> klass){
       List<SelectItem> selectItems = new ArrayList<SelectItem>();
       Enum[] enums = getValues(klass);
       if(enums == null){
           throw new FacesException("Bag parameter in " + klass.getName());
       }

       FacesContext context = FacesContext.getCurrentInstance();
       String bundleName = context.getApplication().getMessageBundle();
       Locale locale = context.getViewRoot().getLocale();

       for (Enum e : enums){
           SelectItem selectItem = new SelectItem();
           selectItem.setLabel(Messages.getMessageResourceString(bundleName, e.toString().toLowerCase(Locale.ENGLISH),
                   null, locale));
           selectItem.setValue(e);
           selectItems.add(selectItem);
       }

       return selectItems;

    }

    private static <T extends Enum<T>> Enum<T>[] getValues(Class<T> klass) {
        try {
                Method m = klass.getMethod("values", null);
                Object obj = m.invoke(null, null);
                return (Enum<T>[])obj;
        } catch(Exception ex) {
                return null;
        }
}

}
